package com.scanner.scannersdk;

import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

import androidx.annotation.Nullable;

import com.scanner.scannersdk.callback.SdkMessage;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Arrays;
import java.util.UUID;

public class BleBlueToothServce extends Service {
    BluetoothDevice bluetoothDevice;
    BluetoothDevice mbluetoothDevice;
    BluetoothAdapter bluetoothAdapter;
    BluetoothGatt gatt;
    BluetoothGattService bluetoothGattService;
    BluetoothGattCharacteristic read_bluetoothGattCharacteristic;
    BluetoothGattCharacteristic write_bluetoothGattCharacteristic;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        bluetoothDevice = intent.getParcelableExtra("bluetoothDevice");
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        mbluetoothDevice = bluetoothAdapter.getRemoteDevice(bluetoothDevice.toString());
        Log.d("tag", "dadas");
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        connectBlueDevce();
        return super.onStartCommand(intent, flags, startId);
    }


    private void connectBlueDevce() {
        mbluetoothDevice.connectGatt(getApplicationContext(), true, new BluetoothGattCallback() {
            @Override
            public void onPhyUpdate(BluetoothGatt gatt, int txPhy, int rxPhy, int status) {
                super.onPhyUpdate(gatt, txPhy, rxPhy, status);
            }

            @Override
            public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
                super.onConnectionStateChange(gatt, status, newState);
                if (newState == BluetoothGatt.STATE_CONNECTED) {
                    Log.e("tag", "设备连接上 开始扫描服务");
                    // 开始扫描服务，安卓蓝牙开发重要步骤之一
                    EventBus.getDefault().post(SdkMessage.getInstance(null,SdkValue.connectbt_success,null));
                    gatt.discoverServices();
                }

                if (newState == BluetoothGatt.STATE_DISCONNECTED) {
                    // 连接断开
                    /*连接断开后的相应处理*/
                }
            }

            @Override
            public void onServicesDiscovered(BluetoothGatt gatt, int status) {
                super.onServicesDiscovered(gatt, status);
                myOnServicesDiscovered(gatt,status);
            }



            private void myOnServicesDiscovered(BluetoothGatt gatt, int status) {
                BleBlueToothServce.this.gatt=gatt;
                bluetoothGattService = gatt.getService(UUID.fromString("0000fff0-0000-1000-8000-00805f9b34fb"));
                if(bluetoothGattService!=null){
                    read_bluetoothGattCharacteristic = bluetoothGattService.getCharacteristic(UUID.fromString("0000fff1-0000-1000-8000-00805f9b34fb"));
                    write_bluetoothGattCharacteristic = bluetoothGattService.getCharacteristic(UUID.fromString("0000fff2-0000-1000-8000-00805f9b34fb"));
                }else {
                    bluetoothGattService=gatt.getService(UUID.fromString("0000ff00-0000-1000-8000-00805f9b34fb"));
                    read_bluetoothGattCharacteristic = bluetoothGattService.getCharacteristic(UUID.fromString("0000ff01-0000-1000-8000-00805f9b34fb"));
                    write_bluetoothGattCharacteristic = bluetoothGattService.getCharacteristic(UUID.fromString("0000ff02-0000-1000-8000-00805f9b34fb"));
                }
                write_bluetoothGattCharacteristic.setValue(ScannerUtil.getCommandBtye(SdkValue.MODE_STYLE));
                gatt.setCharacteristicNotification(read_bluetoothGattCharacteristic, true);
                gatt.readCharacteristic(read_bluetoothGattCharacteristic);
                write_bluetoothGattCharacteristic.setValue(ScannerUtil.getCommandBtye(SdkValue.MODE_STYLE));
                write_bluetoothGattCharacteristic.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT);
                gatt.writeCharacteristic(write_bluetoothGattCharacteristic);

            }


            @Override
            public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
                super.onCharacteristicChanged(gatt, characteristic);
//                Log.d("tag", Arrays.toString(characteristic.getValue()));
                EventBus.getDefault().postSticky(SdkMessage.getInstance("",SdkValue.SdkMessageType_Receve,characteristic.getValue()));
            }

            @Override
            public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
                super.onCharacteristicRead(gatt, characteristic, status);


            }

            @Override
            public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
                super.onCharacteristicWrite(gatt, characteristic, status);

            }

            @Override
            public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
                super.onDescriptorWrite(gatt, descriptor, status);

            }

            @Override
            public void onDescriptorRead(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
                super.onDescriptorRead(gatt, descriptor, status);
                descriptor.getValue();
                Log.d("tag", Arrays.toString(descriptor.getValue()));
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void sendCommand(SdkMessage sdkMessage) {
        switch (sdkMessage.type) {
            case SdkValue.SdkMessageType_Send:
                if(write_bluetoothGattCharacteristic!=null){
                    Log.d("ss",""+Arrays.toString(sdkMessage.s));
                    write_bluetoothGattCharacteristic.setValue(sdkMessage.s);
                    write_bluetoothGattCharacteristic.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT);
                    gatt.writeCharacteristic(write_bluetoothGattCharacteristic);
                }
                break;
            case SdkValue.getSdkMessageType_DisBleBluetoothAndServce:
                EventBus.getDefault().unregister(this);
                gatt.disconnect();
                gatt.close();
                stopSelf();
                break;
        }
    }
}
